package com.example.myapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.text.DecimalFormat;

public class DetailActivity extends AppCompatActivity {

    private TextView tvCurrency;
    private EditText etRmb;
    private Button btnCalculate;
    private TextView tvResult;
    private double exchangeRate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail_activity);

        // 初始化视图组件
        tvCurrency = findViewById(R.id.tv_currency);
        etRmb = findViewById(R.id.et_rmb);
        btnCalculate = findViewById(R.id.btn_calculate);
        tvResult = findViewById(R.id.tv_result);

        // 获取传递的汇率参数
        getIntentData();

        // 设置计算按钮点击事件
        btnCalculate.setOnClickListener(v -> calculateCurrency());
    }

    private void getIntentData() {
        try {
            // 接收前一个页面传递的参数
            String currencyName = getIntent().getStringExtra("currencyName");
            String rateStr = getIntent().getStringExtra("exchangeRate");

            // 参数有效性验证
            if (currencyName == null || rateStr == null) {
                Toast.makeText(this, "数据传递错误", Toast.LENGTH_SHORT).show();
                finish();
                return;
            }

            // 转换汇率值为数字
            exchangeRate = Double.parseDouble(rateStr);
            tvCurrency.setText(currencyName + "汇率计算");
        } catch (NumberFormatException e) {
            Toast.makeText(this, "汇率格式错误", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void calculateCurrency() {
        String rmbStr = etRmb.getText().toString().trim();

        // 输入验证
        if (rmbStr.isEmpty()) {
            Toast.makeText(this, "请输入人民币金额", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            double rmb = Double.parseDouble(rmbStr);
            double result = rmb / (exchangeRate / 100); // 根据汇率计算逻辑调整

            // 格式化显示结果（保留两位小数）
            DecimalFormat df = new DecimalFormat("#0.00");
            String formattedResult = df.format(result);

            tvResult.setText("可兑换金额：\n" + formattedResult);
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效数字", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "计算发生错误", Toast.LENGTH_SHORT).show();
        }
    }
}